//
//  TWChoicenessCacheTool.swift
//  EyepetizerImitative
//
//  Created by 田伟 on 2017/3/24.
//  Copyright © 2017年 个人. All rights reserved.
//  将首页的数据本地化存储的工具类

import UIKit
import FMDB

class TWChoicenessCacheTool: NSObject {
    
    // 单例
    static let shareInstence : TWChoicenessCacheTool = TWChoicenessCacheTool()
    
    // MARK:- 属性
    var db : FMDatabase?
    override init() {
        super.init()
        createFMDB()
    }
}

// MARK:- 初始化数据库
extension TWChoicenessCacheTool {
    fileprivate func createFMDB() {
        // 沙盒地址
        let path = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).first!
//        TWLog(message: path)
        let filePath = path + "/Choiceness.sqlite"
        // 创建数据库对象
        db = FMDatabase(path: filePath)
        if db!.open() {
            createChoicenessTable()
//            createSubscriptionTable()
        } else {
            TWLog(message: "打开数据库失败")
        }
    }
    private func createChoicenessTable() {
        let sql = "CREATE TABLE IF NOT EXISTS tw_choiceness(id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, choiceness_dict blob NOT NULL)"
        let result = db?.executeUpdate(sql, withArgumentsIn: nil)
        if result! {
//            TWLog(message: "创表成功")
        } else {
            TWLog(message: "创表失败")
        }
    }
    private func createSubscriptionTable() {
        let sql = "CREATE TABLE IF NOT EXISTS tw_subscription(id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, subscription_dict blob NOT NULL)"
        let result = db?.executeUpdate(sql, withArgumentsIn: nil)
        if result! {
//            TWLog(message: "创表成功")
        } else {
            TWLog(message: "创表失败")
        }
    }
}

// MARK:- 加载首页的数据
extension TWChoicenessCacheTool {
    func loadChoicenessData(isLoadNewData : Bool, isLoadMoreData: Bool, urlString: String, finished: @escaping (_ result : [String : AnyObject]?, _ error : Error?)->()) {
        
        // MARK:- 将请求下来的数据全部以二进制保存起来，在取的时候有且只能取到一条数据，所有无法判断，加载更多时必须通过网络请求，暂时放这，以后再改
        
        // 从数据库中读取缓存数据
//        let choiceness = cacheChoiceness()
//        if !isLoadNewData {
//            //有数据就传给控制器去加载
//            finished(choiceness, nil)
//        } else {
            // 没有数据就重新下载
            TWNetworkTool.shareInstance.loadChoicenessData(urlString: urlString, finished: { (newResult, error) in
                // 缓存
                if (error != nil) {
                    return
                }
                self.saveChoicenessDictArray(result: newResult!)
                // 把数据传出去
                finished(newResult, error)
            })
//        }
    }
}

// MARK:- 从数据库中读取数据
extension TWChoicenessCacheTool {
    fileprivate func cacheChoiceness() -> [String : AnyObject] {
        var choiceness = [String : AnyObject]()
        // 取出数据
        let resultSet : FMResultSet?
        resultSet = db?.executeQuery("select * from tw_choiceness", withArgumentsIn: nil)
        // 遍历查询结果
        while resultSet!.next() {
            let data = resultSet?.object(forColumnName: "choiceness_dict")
            let dict = NSKeyedUnarchiver.unarchiveObject(with: data as! Data)
            choiceness = dict as! [String : AnyObject]
        }
        return choiceness
    }
}

// MARK:- 将下载下来的数据保存到数据流库里面
extension TWChoicenessCacheTool {
    fileprivate func saveChoicenessDictArray(result : [String : AnyObject]) {
        // 将字典序列化成二进制流
        let data = NSKeyedArchiver.archivedData(withRootObject: result)
        let resultData = db?.executeUpdate("insert into tw_choiceness(choiceness_dict) values(?)", withArgumentsIn: [data])
        if resultData! {
//            TWLog(message: "数据保存成功")
        } else {
            TWLog(message: "保存失败")
        }
    }
}





